package com.lzs.common.utils.wechat.wechatpay;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

@Slf4j
@SuppressWarnings("deprecation")
public class WechatConfig {

    private static SSLConnectionSocketFactory sslcsf;

    public static SSLConnectionSocketFactory getSslcsf(String password, String certPath) {
        if (null == sslcsf) {
            setSsslcsf(password,certPath);
        }
        return sslcsf;
    }

    private static void setSsslcsf(String password, String certPath) {
        try {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
//            Thread.currentThread().getContextClassLoader();
            log.info("微信api证书位置:{}",certPath);
            //InputStream instream = WechatCompanyTransferPersonApiResult.class.getResourceAsStream(ResourceUtil.getConfigByName("wx.certName"));
            try (FileInputStream instream = new FileInputStream(new File(certPath))) {
                keyStore.load(instream, password.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();
            sslcsf = new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        } catch (Exception e) {
            log.error("读取微信api证书异常",e);
        }
    }

}
